import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from .models import UserAddress

User = get_user_model()


class WechatService:
    """微信服务"""

    # 微信小程序配置
    WECHAT_APPID = "wxc66c9ba4701d37b2"
    WECHAT_SECRET = "23094a4697c0cde4d27a387ef2402822"  # 需要配置实际的secret

    @classmethod
    def get_openid_by_code(cls, code):
        """通过code获取openid"""
        # 生产模式：调用微信API
        url = "https://api.weixin.qq.com/sns/jscode2session"
        params = {
            'appid': cls.WECHAT_APPID,
            'secret': cls.WECHAT_SECRET,
            'js_code': code,
            'grant_type': 'authorization_code'
        }

        try:
            response = requests.get(url, params=params, timeout=10)
            data = response.json()

            if 'errcode' in data:
                raise ValidationError(f"微信登录失败: {data.get('errmsg', '未知错误')}")

            return {
                'openid': data.get('openid'),
                'session_key': data.get('session_key'),
                'unionid': data.get('unionid')
            }
        except requests.RequestException as e:
            raise ValidationError(f"网络请求失败: {str(e)}")

    @classmethod
    def login_or_register(cls, code, user_info=None):
        """微信登录或注册"""
        wechat_data = cls.get_openid_by_code(code)
        openid = wechat_data['openid']

        if not openid:
            raise ValidationError("获取微信用户信息失败")

        # 查找或创建用户
        user, created = User.objects.get_or_create(
            openid=openid,
            defaults={
                'username': openid,
                'session_key': wechat_data.get('session_key'),
                'unionid': wechat_data.get('unionid'),
                'nickname': '',  # 默认空昵称，需要用户手动设置
                'avatar': '',  # 默认空头像，需要用户手动设置
            }
        )

        # 更新session_key
        if not created:
            user.session_key = wechat_data.get('session_key')
            user.save()

        return user

    @staticmethod
    def _convert_gender(gender_code):
        """转换性别代码"""
        gender_map = {
            1: 'male',
            2: 'female',
            0: 'unknown'
        }
        return gender_map.get(gender_code, 'unknown')


class UserService:
    """用户服务"""

    @staticmethod
    def get_user_profile(user_id):
        """获取用户资料"""
        try:
            return User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise ValidationError("用户不存在")

    @staticmethod
    def update_user_profile(user_id, data):
        """更新用户资料"""
        try:
            user = User.objects.get(id=user_id)
            for key, value in data.items():
                setattr(user, key, value)
            user.save()
            return user
        except User.DoesNotExist:
            raise ValidationError("用户不存在")

    @staticmethod
    def get_user_addresses(user_id):
        """获取用户地址列表"""
        return UserAddress.objects.filter(user_id=user_id).order_by('-is_default', '-created_at')

    @staticmethod
    def create_user_address(user_id, data):
        """创建用户地址"""
        # 如果设置为默认地址，将其他地址设为非默认
        if data.get('is_default', False):
            UserAddress.objects.filter(user_id=user_id, is_default=True).update(is_default=False)

        # 如果是第一个地址，自动设为默认
        if not UserAddress.objects.filter(user_id=user_id).exists():
            data['is_default'] = True

        return UserAddress.objects.create(user_id=user_id, **data)

    @staticmethod
    def update_user_address(address_id, user_id, data):
        """更新用户地址"""
        try:
            address = UserAddress.objects.get(id=address_id, user_id=user_id)

            # 如果设置为默认地址，将其他地址设为非默认
            if data.get('is_default', False):
                UserAddress.objects.filter(user_id=user_id, is_default=True).exclude(id=address_id).update(is_default=False)

            for key, value in data.items():
                setattr(address, key, value)
            address.save()
            return address
        except UserAddress.DoesNotExist:
            raise ValidationError("地址不存在")

    @staticmethod
    def delete_user_address(address_id, user_id):
        """删除用户地址"""
        try:
            address = UserAddress.objects.get(id=address_id, user_id=user_id)
            was_default = address.is_default
            address.delete()

            # 如果删除的是默认地址，将第一个地址设为默认
            if was_default:
                first_address = UserAddress.objects.filter(user_id=user_id).first()
                if first_address:
                    first_address.is_default = True
                    first_address.save()
        except UserAddress.DoesNotExist:
            raise ValidationError("地址不存在")

    @staticmethod
    def get_default_address(user_id):
        """获取默认地址"""
        return UserAddress.objects.filter(user_id=user_id, is_default=True).first()

    @staticmethod
    def set_default_address(address_id, user_id):
        """设置默认地址"""
        try:
            # 将所有地址设为非默认
            UserAddress.objects.filter(user_id=user_id).update(is_default=False)

            # 设置指定地址为默认
            address = UserAddress.objects.get(id=address_id, user_id=user_id)
            address.is_default = True
            address.save()
            return address
        except UserAddress.DoesNotExist:
            raise ValidationError("地址不存在")


class UserVipService:
    """用户VIP服务"""

    @staticmethod
    def check_vip_status(user_id):
        """检查VIP状态"""
        try:
            user = User.objects.get(id=user_id)
            if user.is_vip and user.vip_expire_time:
                from datetime import datetime
                if user.vip_expire_time < datetime.now():
                    user.is_vip = False
                    user.save()
            return user.is_vip
        except User.DoesNotExist:
            return False

    @staticmethod
    def activate_vip(user_id, days=30):
        """激活VIP"""
        try:
            from datetime import datetime, timedelta
            user = User.objects.get(id=user_id)

            if user.is_vip and user.vip_expire_time and user.vip_expire_time > datetime.now():
                # 如果已经是VIP，延长时间
                user.vip_expire_time += timedelta(days=days)
            else:
                # 新激活VIP
                user.is_vip = True
                user.vip_expire_time = datetime.now() + timedelta(days=days)

            user.save()
            return user
        except User.DoesNotExist:
            raise ValidationError("用户不存在")
